﻿using Authority.Logic;
using Authority.Model;
using Common.Library;
using Document.Library;
using Ioc.Library;
using Microsoft.AspNetCore.Mvc;
using Network.Library;
using Redis.Library;
using System;
using Tool.Model;

namespace Web.Manage.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class LoginController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetValidateCode()
        {
            try
            {
                string code = ValidateCode.CreateValidateCode(4);
                RedisClient.GetRedisDb(ConstParamers.RedisDbWeb).StringSet(ConstParamers.RedisValidateCode, code);
                byte[] bytes = ValidateCode.CreateValidateGraphic(code);
                return File(bytes, @"image/jpeg");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        ///</summary>
        ///登录
        ///</summary>
        public ContentResult LoginCheck()
        {
            var resultInfo = new ResultJsonInfo<AdminTicket>();
            try
            {
                //实体接收数据
                var parametersInfo = DeserializeRequestData<ParametersInfo<LoginRequest>>();

                ISysUserService sysUser = UnityCIContainer.Instance.GetService<ISysUserService>();

                var ValidateCode = RedisClient.GetRedisDb(ConstParamers.RedisDbWeb).StringGet(ConstParamers.RedisValidateCode);

                //验证码验证
                if (ValidateCode.IsNotNullOrEmpty())
                {
                    if (ValidateCode == parametersInfo.parameters.VialdCode)
                    {
                        //数据库验证
                        resultInfo = sysUser.UserLogin(parametersInfo.parameters);

                        //验证通过
                        if (resultInfo != null && resultInfo.Code == ActionCodes.Success)
                        {
                            if (resultInfo.Success)
                            {
                                UserSession.AddLoginUser<AdminTicket>(resultInfo.Data);
                            }
                        }
                    }
                    else
                    {
                        resultInfo.Msg = "验证码不正确！";
                    }
                }
                else
                {
                    resultInfo.Msg = "验证码失效，请重新获取！";
                }
            }
            catch (Exception ex)
            {
                resultInfo.Success = false;
                resultInfo.Excep = ex;
            }
            return ReturnResult(resultInfo);
        }
    }
}